<?php declare(strict_types=1);

namespace app\common\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 接管异常处理 Handle 类
 */
class ExceptionHandle extends Handle
{
    /**
     * @var array
     */
    private array $error = [
        'code' => 50003,
        'msg' => 'error',
        'data' => []
    ];

    public function render($request, Throwable $e): Response
    {
        // 自定义参数验证
        if ($e instanceof DilumaException) {
            $this->error = array_merge($this->error, $e->error);
            return json($this->error);
        }
        // 参数验证错误
        if ($e instanceof ValidateException) {
            $this->error['msg'] = is_array($e->getError()) ? implode(';', $e->getError()) : $e->getMessage();
            return json($this->error);
        }

        // 请求异常
        if ($e instanceof HttpException && $request->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}